from boss_fight import Boss_fight
from data_loader import load_boss, load_player
import json
from datetime import datetime

def run_simulation(player_name, boss_name, isSavelog, count):
    player = load_player(player_name)
    boss = load_boss(boss_name)
    wincount = 0
    drawcount = 0
    if player is None or boss is None:
        print("Player or boss not found!")
        return
    
    play_list, suc = Boss_fight(player, boss)
    wincount = 1 if suc == '群友赢了' else 0
    drawcount = 1 if suc == '战斗超过20回合，未能战胜！' else 0
    print(f"Battle Result: {suc}")
    
    # Print and store the play_list as a log
    if isSavelog:# and wincount == 0 and drawcount == 0:
        log_filename = f"battle_log_{player_name}_vs_{boss_name}_game{count+1}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
    
        with open('log/'+log_filename, 'w', encoding='utf-8') as log_file:
            for turn in play_list:
                log_entry = turn["content"]#json.dumps(turn, ensure_ascii=False)
                print(log_entry)
                log_file.write(log_entry + '\n')
    
        print(f"Battle log saved to {log_filename}")
    return wincount, drawcount

if __name__ == "__main__":
    player_name = input("Enter player name: ")
    boss_name = input("Enter boss name: ")
    repeattimes = int(input("Enter the number of battles to simulate: "))
    if repeattimes > 10:
        print("More than 10 games. Log saving is defaultly disabled.")
        isSavelog = input("Do you want to save the battle log? (y/n): (WARNING: This may cause significant performance issues!)") == 'y'
    else:
        isSavelog = True
        print("Log saving is enabled to show the details of each battle.")
        # isSavelog = input("Do you want to save the battle log? (y/n): (WARNING: This may cause significant performance issues!)") == 'y'
    wingames = 0
    drawgames = 0
    count = 0
    while count < repeattimes:
        winning, drawing = run_simulation(player_name, boss_name, isSavelog, count)
        wingames, drawgames = wingames + winning, drawgames + drawing
        count += 1
    print(f"{player_name} vs {boss_name} 共{repeattimes}场对战，获胜{wingames}场，平局{drawgames}场，败北{repeattimes-wingames-drawgames}，胜率: {wingames/repeattimes*100:.2f}%")